	package com.halloon.android.ui.fragment;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragment;
import com.halloon.android.R;
import com.halloon.android.adapter.ContactAdapter;
import com.halloon.android.bean.UserBean;
import com.halloon.android.data.ContentManager;
import com.halloon.android.data.DBManager;
import com.halloon.android.data.SettingsManager;
import com.halloon.android.util.Constants;
import com.halloon.android.util.PopupWindowManager;
import com.lhws.components.widget.indexer.IndexableListView;

public class TabMyContactsFragment extends SherlockFragment implements OnTouchListener, OnItemClickListener, OnClickListener{
	private Context context;
	private IndexableListView listView;
	private View loadingView;
	private EditText searchEditText;
	private Button deleteButton;
	private Button addButton;
	private TextView titleText;
	private ArrayList<UserBean> listItems;
	private ContactAdapter adapter;
	private  ContactsFragmentCallback cfCallback;
	
	public interface ContactsFragmentCallback{
		public void setupLBSContactFragment();
		public void setupProfileFragment(Bundle bundle);
	}
	
	@Override
	public void onAttach(Activity activity){
		super.onAttach(activity);
		this.cfCallback = (ContactsFragmentCallback) activity;
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View root = inflater.inflate(R.layout.tab_my_contacts, null, false);
		listView = (IndexableListView) root.findViewById(R.id.listview);
		loadingView = root.findViewById(R.id.loading);
		searchEditText = (EditText) root.findViewById(R.id.search_editText);
		deleteButton = (Button) root.findViewById(R.id.deleteButton);
		addButton = (Button) root.findViewById(R.id.add_button);
		titleText = (TextView) root.findViewById(R.id.title_text);
		return root;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		context = getSherlockActivity();
		
		listItems = new ArrayList<UserBean>();
		adapter = new ContactAdapter(context, R.layout.list_item_contact, listItems);
		listView.setAdapter(adapter);
		listView.setAreHeadersSticky(false);
		listView.setFastScrollEnabled(true);
		listView.setOnTouchListener(this);
		listView.setOnItemClickListener(this);
		searchEditText.addTextChangedListener(textWatcher);
		deleteButton.setOnClickListener(this);
		addButton.setOnClickListener(this);
		titleText.setClickable(true);
		titleText.setOnClickListener(this);
		loadData();
		
	}
	
	public void loadData() {
		Log.d(Constants.LOG_TAG, "loadData");

		AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
			@Override
			protected void onPreExecute() {
				loadingView.setVisibility(View.VISIBLE);
				listView.setVisibility(View.GONE);
			}
			@Override
			protected String doInBackground(Void... arg0) {
				
				long a = System.currentTimeMillis();

				if (SettingsManager.getInstance(context).getContactStatus() == DBManager.CONTACT_STATUS_INIT) {
					Log.d(Constants.LOG_TAG, "loadData Net");
					ArrayList<UserBean> tmpArrayList = ContentManager.getInstance(context).getContacts();
					
					HashMap<String, UserBean> unduplicatedContacts = new HashMap<String, UserBean>();
					for(int i=0; i<tmpArrayList.size(); i++) {
						unduplicatedContacts.put(tmpArrayList.get(i).getOpenId(), (UserBean)tmpArrayList.get(i));
						
					}
					
					DBManager.getInstance(context).addContacts(unduplicatedContacts, false);
					listItems.addAll(tmpArrayList);
				} else {
					Log.d(Constants.LOG_TAG, "loadData DB");
					listItems.addAll(DBManager.getInstance(context).getAllContacts());
				}
				long b = System.currentTimeMillis();

				Log.d(Constants.LOG_TAG, ">>>>>>>>>>>>>>>request time in : "+(b-a)+" ms");

				return "";
			}
			
			@Override
			protected void onPostExecute(String result) {

				adapter.notifyDataSetChanged();
							
				if (SettingsManager.getInstance(context).getContactStatus() == DBManager.CONTACT_STATUS_READY) {
					requestData();
				}
				loadingView.setVisibility(View.GONE);
				listView.setVisibility(View.VISIBLE);
			}

		};

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
		} else {
			task.execute();
		}
	}
	

	public void requestData() {
		Log.d(Constants.LOG_TAG, "requestData");

		AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
			@Override
			protected void onPreExecute() {

			}
			@Override
			protected String doInBackground(Void... arg0) {
				ArrayList<UserBean> tmpArrayList = ContentManager.getInstance(context).getContacts();
				if (tmpArrayList.size()!=0) {
					HashMap<String, UserBean> unduplicatedContacts = new HashMap<String, UserBean>();
					for(int i=0; i<tmpArrayList.size(); i++) {
						unduplicatedContacts.put(tmpArrayList.get(i).getOpenId(), (UserBean)tmpArrayList.get(i));
						
					}					
					DBManager.getInstance(context).addContacts(unduplicatedContacts, true);
					listItems.clear();
					listItems.addAll(DBManager.getInstance(context).getAllContacts());
					Log.d(Constants.LOG_TAG, "requestData "+listItems.size());
				}else {
					return "";
				}			
				return "ok";
			}
			
			@Override
			protected void onPostExecute(String result) {
				if (result.equals("ok")) {
					adapter.notifyDataSetChanged();
					Toast.makeText(context, "update finish", Toast.LENGTH_SHORT).show();
				}else {
					Toast.makeText(context, "update failure", Toast.LENGTH_SHORT).show();
				}

			}

		};

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
		} else {
			task.execute();
		}
	}
	
	private TextWatcher textWatcher = new TextWatcher() {

		public void onTextChanged(CharSequence s, int start, int before, int count) {
			Log.d(Constants.LOG_TAG, "onTextChanged "+s.toString());
			ArrayList<UserBean> tmpArrayList = DBManager.getInstance(context).getContactsSearch(s.toString());
			listItems.clear();
			listItems.addAll(tmpArrayList);
			adapter.notifyDataSetChanged();
			if (s.length() == 0) {
				deleteButton.setVisibility(View.INVISIBLE);
			}else {
				deleteButton.setVisibility(View.VISIBLE);
			}
		}
		
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			
		}
		
		public void afterTextChanged(Editable s) {
			
		}
		
	};

	public boolean onTouch(View v, MotionEvent event) {
		InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(searchEditText.getWindowToken(), 0);
		return false;
	}

	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		Bundle bundle = new Bundle();
		bundle.putString("name", listItems.get(position).getName());
		((InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(((Activity) context).getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		cfCallback.setupProfileFragment(bundle);
	}

	public void onClick(View v) {
		switch(v.getId()){
		case R.id.deleteButton:
			searchEditText.setText("");
		break;
		case R.id.add_button:
			((InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(((Activity) context).getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
			cfCallback.setupLBSContactFragment();
		break;
		case R.id.title_text:
			PopupWindowManager pwManager = new PopupWindowManager(context);
			ArrayList<String> arrayList = new ArrayList<String>();
			arrayList.add("好友");
			arrayList.add("关注");
			arrayList.add("粉丝");
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, arrayList);
			pwManager.setupTitleListPopup(R.id.title_text, adapter);
		}
	}
}
